package pe.gob.osce.sirenas.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import pe.gob.osce.sirenas.dao.ViaDAOLocal;
import pe.gob.osce.sirenas.dao.convert.ViaConvert;
import pe.gob.osce.sirenas.dao.convert.ZonaConvert;
import pe.gob.osce.sirenas.model.ViaDTO;
import pe.gob.osce.sirenas.model.jpa.Via;
import pe.gob.osce.sirenas.util.ConstanteEJB;
import pe.gob.osce.sirenas.util.ModeloException;


@Stateless
public class ViaDAOImpl implements ViaDAOLocal {

	@PersistenceContext(unitName="pe.gob.osce.sirenas.be.pu" )
	private	EntityManager	em;
	ResourceBundle propSirenas = ResourceBundle.getBundle(ConstanteEJB.PROPERTIES);

	@Override 
	public List<ViaDTO> listaVias() throws Exception{

		List<ViaDTO> listaViasDTO=null;
		try{
			StringBuilder  	jpql= new StringBuilder();
						
			jpql.append("SELECT va FROM Via va WHERE va.estado= 1");
			Query	query= em.createQuery( jpql.toString() );
			
			List<Via>	listaObjeto= query.getResultList();
			listaViasDTO=ViaConvert.createListaViaDTO(listaObjeto);
		} catch (NoResultException nre) {
			listaViasDTO=new ArrayList<ViaDTO>();
			 throw new ModeloException(propSirenas.getString(ConstanteEJB.EXC_MODELO_NO_DATA));
		}catch (Exception e) {
			throw new ModeloException(propSirenas.getString(ConstanteEJB.EXC_MODELO_GENERAL_DB), e);
		}
		return listaViasDTO;
	}
	
	@Override
	public Via insertVia(Via via) throws Exception {
		try{
			em.merge(via);
			em.flush();
		} catch (Exception e) {
			throw new ModeloException(propSirenas.getString(ConstanteEJB.EXC_MODELO_NO_INSERT), e);
		}
		return via;
	}
	
}
